package chapter14;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : DuJiabao
 * @Date : 2021/2/25 8:48
 * @Project : thinking_in_java
 * @File : null.java
 * @Desc :
 */
public class FilledList<T> {
  private Class<T> type;

  public FilledList(Class<T> type) {
    this.type = type;
  }

  public List<T> create(int nElements) {
    List<T> result = new ArrayList<T>();
    try {
      for (int i = 0; i < nElements; i++) {
        result.add(type.getDeclaredConstructor().newInstance());
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return result;
  }

  public static void main(String[] args) {
    FilledList<CountedInteger> fl = new FilledList<>(CountedInteger.class);
    System.out.println(fl.create(15));
  }
}

class CountedInteger {
  private static long counter;  // 用来计数的
  private final long id = counter++;  // 每个对象都有一个唯一的id

  public String toString() {
    return Long.toString(id);
  }
}

